package com.example.selenium.util;

import com.example.selenium.service.impl.AsyncServiceImpl;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * @Author : 刘思盖
 * @Date : 2021/9/18 18:59
 */
@Slf4j
public class FileUtils {

    /**
     * 创建文件夹
     * @param directory
     * @return
     */
    public static boolean mkdirs(String directory){
        File file = new File(directory);
        try{
            if(!file.exists()&&!file.isDirectory()) {
                file.mkdirs();
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 将运单信息写入文件
     * @param filePath
     * @param data
     */
    public static void writeInTxt(String filePath,String data){
        FileWriter fileWritter = null;
        try {
            fileWritter = new FileWriter(filePath,true);
            fileWritter.write(data);
            fileWritter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 写入文件
     * @param directory 文件夹路径
     * @param fileName 文件名称
     * @param data 写入数据
     */
    public static void witeInTxt(String directory,String fileName,String data){
        boolean b = FileUtils.mkdirs(directory);
        if(b){
            String filePath = directory+"\\"+fileName+".txt";
            // 避免重复写入，先将该文件删除
            File file = new File(filePath);
            if(file.exists()){
                file.delete();
            }
            log.info("正在写入文件，线程id="+Thread.currentThread().getName());
            FileUtils.writeInTxt(filePath,data);
            log.info(filePath+"写入完毕");
        }
    }

    /**
     * 生成运单的文件夹
     * @param trackId
     * @return
     */
    public static String createDirectory(String trackId,String directoryType){
        String year = trackId.substring(1,5);
        String month = trackId.substring(5,7);
        String day = trackId.substring(7,9);
        String directory = "E:\\"+ AsyncServiceImpl.DIRECTORY_ALL+"\\"+year+"\\"+month+"\\"+day+"\\"+directoryType;
        boolean b = FileUtils.mkdirs(directory);
        if(b){
            return directory;
        }else{
            return "";
        }
    }


}
